const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const path = require('path');
const { generateCaptcha } = require('./utils/captcha');
const XLSX = require('xlsx');
const bcrypt = require('bcrypt');

const app = express();
app.use(express.json()); // 解析JSON请求体
const server = http.createServer(app);
const io = new Server(server);

// 存储验证码
const captchaStore = new Map();

// 获取验证码
app.get('/captcha', (req, res) => {
  const captchaText = generateCaptcha();
  const captchaId = Date.now().toString();
  captchaStore.set(captchaId, captchaText);
  
  // 设置验证码有效期（5分钟）
  setTimeout(() => {
    captchaStore.delete(captchaId);
  }, 5 * 60 * 1000);

  res.json({
    id: captchaId,
    text: captchaText
  });
});

// 修改读取用户数据的路径
function readUserData() {
  try {
    const workbook = XLSX.readFile(path.join(__dirname, 'data', 'user.xlsx'));
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const users = XLSX.utils.sheet_to_json(sheet);
    console.log('读取到的用户数据:', JSON.stringify(users, null, 2));
    return users;
  } catch (error) {
    console.error('读取用户数据失败:', error);
    return [];
  }
}

// 存储用户数据
const userData = readUserData();

// 修改登录接口的验证逻辑
app.post('/login', async (req, res) => {
  const { username, password, captchaId, captchaText } = req.body;
  
  // 每次登录时重新读取用户数据
  const users = readUserData();
  
  console.log('登录请求:', { username, password });
  console.log('存储的用户数据:', users);
  
  // 验证验证码
  const storedCaptcha = captchaStore.get(captchaId);
  if (!storedCaptcha || storedCaptcha.toLowerCase() !== captchaText.toLowerCase()) {
    console.log('验证码验证失败');
    return res.status(400).json({ error: '验证码错误' });
  }
  
  // 查找用户
  const user = users.find(u => u.username === username);
  console.log('找到的用户:', user);
  
  if (!user) {
    console.log('未找到用户');
    return res.status(400).json({ error: '用户名或密码错误' });
  }

  // 验证密码
  try {
    const passwordMatch = await bcrypt.compare(password, user.password);
    console.log('密码验证结果:', passwordMatch);
    
    if (!passwordMatch) {
      console.log('密码不匹配');
      return res.status(400).json({ error: '用户名或密码错误' });
    }
    
    console.log('登录成功');
    // 登录成功
    res.json({ 
      success: true,
      username: username
    });
  } catch (error) {
    console.error('密码验证出错:', error);
    return res.status(400).json({ error: '登录失败，请重试' });
  }
});

// 路由
app.get('/', (req, res) => {
  res.redirect('/login'); // 将根路径重定向到登录页
});

app.get('/login', (req, res) => {
  res.sendFile(path.join(__dirname, 'public/login.html'));
});

app.get('/index', (req, res) => {
  res.sendFile(path.join(__dirname, 'public/index.html')); // 原 home.html
});

app.get('/chat', (req, res) => {
  res.sendFile(path.join(__dirname, 'public/chat.html')); // 原 index.html
});

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 用户连接处理
const users = new Map();

io.on('connection', (socket) => {
  // 用户加入
  socket.on('join', (nickname) => {
    users.set(socket.id, nickname);
    socket.broadcast.emit('message', `${nickname} 加入了聊天室`);
  });

  // 消息处理
  socket.on('message', (msg) => {
    const nickname = users.get(socket.id);
    const timestamp = new Date().toLocaleString('zh-CN', {
      hour12: false,
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
    io.emit('message', {
      nickname,
      message: msg,
      timestamp
    });
  });

  // 用户断开
  socket.on('disconnect', () => {
    const nickname = users.get(socket.id);
    if (nickname) {
      io.emit('message', `${nickname} 离开了聊天室`);
      users.delete(socket.id);
    }
  });
});

// 启动服务
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
